package interview;

import java.util.LinkedList;

public class interview_16_26 {
    public int calculate(String s) {
        LinkedList<Character> sig=new LinkedList<>();
        LinkedList<Integer> num=new LinkedList<>();
        s=s.trim();
        int tmp=0;
        int index=0;
        while(index<s.length()&&s.charAt(index)>='0'&&s.charAt(index)<='9'){
            tmp=10*tmp+(s.charAt(index)-'0');
            index++;
        }
        num.add(tmp);
        tmp=0;
        for(int i=index;i<s.length();){
            while(s.charAt(i)==' ') i++;
            if(s.charAt(i)=='+'||s.charAt(i)=='-'){
                sig.add(s.charAt(i));
                i++;
                while(s.charAt(i)==' ') i++;
                tmp=0;
                while(i<s.length()&&s.charAt(i)>='0'&&s.charAt(i)<='9'){
                    tmp=10*tmp+(s.charAt(i)-'0');
                    i++;
                }
                num.add(tmp);

            }else if(s.charAt(i)=='*'){
                int a=num.removeLast();
                i++;
                while(s.charAt(i)==' ') i++;
                tmp=0;
                while(i<s.length()&&s.charAt(i)>='0'&&s.charAt(i)<='9'){
                    tmp=10*tmp+(s.charAt(i)-'0');
                    i++;
                }
                num.add(a*tmp);

            }else{
                int a=num.removeLast();
                i++;
                while(s.charAt(i)==' ') i++;
                tmp=0;
                while(i<s.length()&&s.charAt(i)>='0'&&s.charAt(i)<='9'){
                    tmp=10*tmp+(s.charAt(i)-'0');
                    i++;
                }
                num.add(a/tmp);
            }
        }
        while(sig.size()!=0){
            char o=sig.removeFirst();
            int a=num.removeFirst();
            int b=num.removeFirst();
            if(o=='+'){
                num.addFirst(a+b);
            }else{
                num.addFirst(a-b);
            }
        }
        return num.getFirst();
    }
}
